import traceback
from models.hotspot import Hotspot
from extensions import db
from services.platform_crawl_manager import (
    get_platform_latest_crawl_at,
    set_platform_latest_crawl_at,
)
from services.constants import PLATFORM_CONFIG
from services.utils import prepare_hotspot_data, format_paginated_result
from crawlers.sspai import get_latest_articles_from_sspai, get_recommended_articles_from_sspai


def fetch_sspai_hotspot_to_db(crawl_at) -> None:
    """抓取少数派热点数据并存入数据库

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    """
    try:
        # 获取少数派热榜数据
        latest_articles = get_latest_articles_from_sspai()

        recommended_articles = get_recommended_articles_from_sspai()

        new_latest_articles = prepare_hotspot_data(latest_articles, "少数派", "最新", crawl_at)
        
        new_recommended_articles = prepare_hotspot_data(recommended_articles, "少数派", "推荐", crawl_at)

        new_articles = [*new_latest_articles, *new_recommended_articles]
        # 批量插入数据到数据库
        if new_articles:
            db.session.bulk_insert_mappings(Hotspot, new_articles)
            db.session.commit()

        # 更新平台最新抓取时间
        set_platform_latest_crawl_at("少数派", crawl_at)

        print("少数派最新数据抓取并存入数据库成功")

    except Exception as e:
        db.session.rollback()
        print("少数派最新数据抓取并存入数据库失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e


def get_latest_sspai_hotspot_from_db() -> list:
    """从数据库获取少数派最新数据

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    Returns:
      最新数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("少数派")

        # 从数据库获取新榜数据
        sspai_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["少数派"]["id"],
            section=PLATFORM_CONFIG["少数派"]["sections"]["最新"],
            crawl_at=latest_crawl_at,
        ).all()

        return sspai_hotspots

    except Exception as e:
        print("从数据库中获取少数派最新榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    
def get_recommend_sspai_hotspot_from_db() -> list:
    """从数据库获取少数派推荐数据

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    Returns:
      推荐数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("少数派")

        # 从数据库获取新榜数据
        sspai_recommendspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["少数派"]["id"],
            section=PLATFORM_CONFIG["少数派"]["sections"]["推荐"],
            crawl_at=latest_crawl_at,
        ).all()

        return sspai_recommendspots

    except Exception as e:
        print("从数据库中获取少数派最新榜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    

def get_latest_sspai_hotspot_from_db_page(page: int, page_size: int) -> list:
    """从数据库获取少数派最新数据

    Parameters:
        page: 页码
        page_size: 每页大小

    Returns:
        最新数据列表
        {
            "pages": 总页数,
            "page": 当前页码,
            "per_page": 每页大小,
            "items": 最新数据列表,
            "total": 总数据条数}
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("少数派")

        # 从数据库获取最新数据，并根据order排序
        sspai_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["少数派"]["id"],
            section=PLATFORM_CONFIG["少数派"]["sections"]["最新"],
            crawl_at=latest_crawl_at,
        ).order_by(Hotspot.order).paginate(page=page, per_page=page_size)

        return format_paginated_result(sspai_hotspots)

    except Exception as e:
        print("从数据库中获取少数派最新数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e
    
def get_recommend_sspai_hotspot_from_db_page(page: int, page_size: int) -> list:
    """从数据库获取少数派推荐数据

    Parameters:
        page: 页码
        page_size: 每页大小

    Returns:
        推荐数据列表
        {
            "pages": 总页数,
            "page": 当前页码,
            "per_page": 每页大小,
            "items": 推荐数据列表,
            "total": 总数据条数}
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("少数派")

        # 从数据库获取推荐数据，并根据order排序
        sspai_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["少数派"]["id"],
            section=PLATFORM_CONFIG["少数派"]["sections"]["推荐"],
            crawl_at=latest_crawl_at,
        ).order_by(Hotspot.order).paginate(page=page, per_page=page_size)

        return format_paginated_result(sspai_hotspots)

    except Exception as e:
        print("从数据库中获取少数派推荐数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e